import React, { useState, useEffect } from 'react';
import { Box, Typography, Card, CardContent, Grid, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Button, TextField, Dialog, DialogTitle, DialogContent, DialogActions, FormControl, InputLabel, Select, MenuItem, Tabs, Tab, Divider, Chip, Avatar, CircularProgress, Alert, AlertTitle } from '@mui/material';
import { Warning, LocationOn, CalendarToday, Clock, Search, Refresh, FilterList, Info, Share, DirectionsCar, LocalParking, Traffic, FlashOn } from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { apiRequest } from '../utils/api';

const PublicData = () => {
  const [trafficData, setTrafficData] = useState([]);
  const [parkingData, setParkingData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [userData, setUserData] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [currentTab, setCurrentTab] = useState(0);
  const [selectedTrafficEvent, setSelectedTrafficEvent] = useState(null);
  const [selectedParkingLot, setSelectedParkingLot] = useState(null);
  const [trafficDialogOpen, setTrafficDialogOpen] = useState(false);
  const [parkingDialogOpen, setParkingDialogOpen] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    // 获取用户信息
    const savedUserInfo = localStorage.getItem('userInfo');
    if (savedUserInfo) {
      try {
        const userInfo = JSON.parse(savedUserInfo);
        setUserData(userInfo);
      } catch (error) {
        console.error('Failed to parse user info:', error);
      }
    }

    // 加载公共数据
    const loadData = async () => {
      try {
        setLoading(true);
        
        // 获取交通和停车统计数据
        const [trafficResponse, parkingResponse] = await Promise.all([
          apiRequest.get('/api/vehicle-data/traffic-stats'),
          apiRequest.get('/api/vehicle-data/parking-stats')
        ]);
        
        // 转换为前端需要的格式
        const trafficStats = trafficResponse.data;
        const parkingStats = parkingResponse.data;
        
        // 交通数据格式
        const traffic = [
          {
            id: 'traffic-beijing',
            type: 'congestion',
            title: '北京市区交通状况',
            description: `当前拥堵指数：${Math.round((trafficStats.totalVehicles - trafficStats.activeVehicles) / trafficStats.totalVehicles * 100)}%，平均车速：${trafficStats.avgSpeed}km/h`,
            location: '北京市区',
            severity: trafficStats.avgSpeed < 20 ? 'high' : trafficStats.avgSpeed < 40 ? 'medium' : 'low',
            startTime: new Date().toISOString(),
            endTime: null,
            latitude: 39.9042,
            longitude: 116.4074,
            status: 'ongoing',
            updateTime: new Date().toISOString(),
            source: '实时路况'
          }
        ];
        
        // 停车数据格式
        const parking = [
          {
            id: 'parking-main',
            name: '主要停车场',
            address: '北京市区主要停车场',
            totalSpaces: parkingStats.totalParked + parkingStats.availableSpots,
            availableSpaces: parkingStats.availableSpots,
            latitude: 39.9042,
            longitude: 116.4074,
            hourlyRate: 10,
            isOpen: true,
            lastUpdated: new Date().toISOString(),
            rating: 4.0,
            features: ['实时监控', '数据共享']
          }
        ];
        
        setTrafficData(traffic);
        setParkingData(parking);
        setError(null);
      } catch (err) {
        console.error('Failed to load public data:', err);
        setError('Failed to load public data. Please try again later.');
        
        // 如果API调用失败，回退到模拟数据
        if (process.env.NODE_ENV === 'development') {
          const mockTrafficData = generateMockTrafficData();
          const mockParkingData = generateMockParkingData();
          setTrafficData(mockTrafficData);
          setParkingData(mockParkingData);
        }
      } finally {
        setLoading(false);
      }
    };

    loadData();
    
    // 每30秒刷新一次数据
    const interval = setInterval(loadData, 30000);
    return () => clearInterval(interval);
  }, []);

  // 生成模拟交通数据
  const generateMockTrafficData = () => {
    const events = [
      {
        id: 'traffic1',
        type: 'accident',
        title: '东三环发生交通事故',
        description: '东三环中路国贸桥附近发生交通事故，造成车辆拥堵，请绕行。',
        location: '东三环中路国贸桥',
        severity: 'high',
        startTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
        endTime: null,
        latitude: 39.9123,
        longitude: 116.4378,
        status: 'ongoing',
        updateTime: new Date().toISOString(),
        source: '交通部门'
      },
      {
        id: 'traffic2',
        type: 'roadwork',
        title: '西二环道路施工',
        description: '西二环南段从今日起进行道路维修，预计持续一周，请提前规划路线。',
        location: '西二环南段',
        severity: 'medium',
        startTime: new Date(Date.now() - 5 * 60 * 60 * 1000).toISOString(),
        endTime: new Date(Date.now() + 6 * 24 * 60 * 60 * 1000).toISOString(),
        latitude: 39.8923,
        longitude: 116.3678,
        status: 'ongoing',
        updateTime: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
        source: '交通部门'
      },
      {
        id: 'traffic3',
        type: 'congestion',
        title: '北四环严重拥堵',
        description: '北四环望和桥至健翔桥段因晚高峰出现严重拥堵，预计等待时间较长。',
        location: '北四环望和桥至健翔桥',
        severity: 'high',
        startTime: new Date(Date.now() - 90 * 60 * 1000).toISOString(),
        endTime: null,
        latitude: 39.9923,
        longitude: 116.3978,
        status: 'ongoing',
        updateTime: new Date(Date.now() - 15 * 60 * 1000).toISOString(),
        source: '实时路况'
      },
      {
        id: 'traffic4',
        type: 'event',
        title: '天安门广场有大型活动',
        description: '天安门广场今日有大型活动，周边道路实施交通管制，请绕行。',
        location: '天安门广场周边',
        severity: 'medium',
        startTime: new Date(Date.now() - 3 * 60 * 60 * 1000).toISOString(),
        endTime: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(),
        latitude: 39.9087,
        longitude: 116.3975,
        status: 'ongoing',
        updateTime: new Date(Date.now() - 60 * 60 * 1000).toISOString(),
        source: '交警部门'
      },
      {
        id: 'traffic5',
        type: 'weather',
        title: '暴雨预警',
        description: '北京市气象台发布暴雨蓝色预警，预计未来3小时内我市将出现强降雨，请注意交通安全。',
        location: '全市范围',
        severity: 'medium',
        startTime: new Date(Date.now() - 60 * 60 * 1000).toISOString(),
        endTime: new Date(Date.now() + 3 * 60 * 60 * 1000).toISOString(),
        latitude: 0,
        longitude: 0,
        status: 'ongoing',
        updateTime: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
        source: '气象局'
      }
    ];
    return events;
  };

  // 生成模拟停车数据
  const generateMockParkingData = () => {
    const parkingLots = [
      {
        id: 'park1',
        name: '国贸中心停车场',
        address: '朝阳区建国门外大街1号',
        totalSpaces: 1500,
        availableSpaces: 350,
        latitude: 39.9123,
        longitude: 116.4378,
        hourlyRate: 15,
        isOpen: true,
        lastUpdated: new Date().toISOString(),
        rating: 4.5,
        features: ['24小时开放', '充电桩', '安保监控']
      },
      {
        id: 'park2',
        name: '西单大悦城停车场',
        address: '西城区西单北大街131号',
        totalSpaces: 1200,
        availableSpaces: 180,
        latitude: 39.8923,
        longitude: 116.3678,
        hourlyRate: 12,
        isOpen: true,
        lastUpdated: new Date().toISOString(),
        rating: 4.2,
        features: ['24小时开放', '电梯直达商场']
      },
      {
        id: 'park3',
        name: '望京SOHO停车场',
        address: '朝阳区望京街8号',
        totalSpaces: 800,
        availableSpaces: 120,
        latitude: 39.9923,
        longitude: 116.4978,
        hourlyRate: 10,
        isOpen: true,
        lastUpdated: new Date().toISOString(),
        rating: 4.0,
        features: ['充电桩', '智能导航']
      },
      {
        id: 'park4',
        name: '北京南站停车场',
        address: '丰台区永外大街车站路12号',
        totalSpaces: 2000,
        availableSpaces: 650,
        latitude: 39.8651,
        longitude: 116.3786,
        hourlyRate: 8,
        isOpen: true,
        lastUpdated: new Date().toISOString(),
        rating: 3.8,
        features: ['24小时开放', '高铁直达']
      },
      {
        id: 'park5',
        name: '奥林匹克公园停车场',
        address: '朝阳区科荟路33号',
        totalSpaces: 1500,
        availableSpaces: 800,
        latitude: 40.0023,
        longitude: 116.3978,
        hourlyRate: 6,
        isOpen: true,
        lastUpdated: new Date().toISOString(),
        rating: 4.3,
        features: ['大型车停车位', '无障碍车位']
      }
    ];
    return parkingLots;
  };

  // 格式化时间戳
  const formatTimestamp = (timestamp) => {
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  };

  // 获取事件类型图标
  const getEventTypeIcon = (type) => {
    switch (type) {
      case 'accident':
        return <Warning size={16} color="error" />;
      case 'roadwork':
        return <Traffic size={16} color="warning" />;
      case 'congestion':
        return <DirectionsCar size={16} color="primary" />;
      case 'event':
        return <Info size={16} color="info" />;
      case 'weather':
        return <FlashOn size={16} color="warning" />;
      default:
        return <Info size={16} color="default" />;
    }
  };

  // 获取事件类型文本
  const getEventTypeText = (type) => {
    switch (type) {
      case 'accident':
        return '交通事故';
      case 'roadwork':
        return '道路施工';
      case 'congestion':
        return '交通拥堵';
      case 'event':
        return '大型活动';
      case 'weather':
        return '天气预警';
      default:
        return type;
    }
  };

  // 获取事件严重程度样式
  const getSeverityStyle = (severity) => {
    switch (severity) {
      case 'high':
        return { color: 'error.main', backgroundColor: 'error.light' };
      case 'medium':
        return { color: 'warning.main', backgroundColor: 'warning.light' };
      case 'low':
        return { color: 'info.main', backgroundColor: 'info.light' };
      default:
        return { color: 'text.primary', backgroundColor: 'background.paper' };
    }
  };

  // 获取事件严重程度文本
  const getSeverityText = (severity) => {
    switch (severity) {
      case 'high':
        return '严重';
      case 'medium':
        return '中等';
      case 'low':
        return '轻微';
      default:
        return severity;
    }
  };

  // 获取停车场可用率
  const getAvailabilityRate = (parkingLot) => {
    return ((parkingLot.availableSpaces / parkingLot.totalSpaces) * 100).toFixed(1);
  };

  // 获取停车场状态样式
  const getParkingStatusStyle = (parkingLot) => {
    const rate = parseFloat(getAvailabilityRate(parkingLot));
    if (rate > 30) {
      return { color: 'success.main' };
    } else if (rate > 10) {
      return { color: 'warning.main' };
    } else {
      return { color: 'error.main' };
    }
  };

  // 打开交通事件详情对话框
  const handleOpenTrafficDialog = (event) => {
    setSelectedTrafficEvent(event);
    setTrafficDialogOpen(true);
  };

  // 关闭交通事件详情对话框
  const handleCloseTrafficDialog = () => {
    setTrafficDialogOpen(false);
    setSelectedTrafficEvent(null);
  };

  // 打开停车场详情对话框
  const handleOpenParkingDialog = (parkingLot) => {
    setSelectedParkingLot(parkingLot);
    setParkingDialogOpen(true);
  };

  // 关闭停车场详情对话框
  const handleCloseParkingDialog = () => {
    setParkingDialogOpen(false);
    setSelectedParkingLot(null);
  };

  // 过滤交通事件
  const filteredTrafficEvents = trafficData.filter(event => 
    event.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
    event.location.toLowerCase().includes(searchTerm.toLowerCase()) ||
    event.description.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // 过滤停车场
  const filteredParkingLots = parkingData.filter(lot => 
    lot.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    lot.address.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <Box sx={{ p: 3 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 2 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          <span style={{ display: 'flex', alignItems: 'center' }}>
            <Info sx={{ mr: 2 }} />
            公共数据监控
          </span>
        </Typography>
      </div>
      
      {loading && (
        <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', py: 4 }}>
          <CircularProgress />
          <Typography variant="body1" sx={{ mt: 2 }}>从数据库加载数据中...</Typography>
        </Box>
      )}
      
      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          <AlertTitle>加载失败</AlertTitle>
          {error}
        </Alert>
      )}
      
      {!loading && (
        <>
          {/* 搜索和过滤区域 */}
          <Card sx={{ mb: 4 }}>
            <CardContent>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <TextField
                  label="搜索"
                  variant="outlined"
                  size="small"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  InputProps={{ startAdornment: <Search size="small" />, style: { width: 300 } }}
                />
                <Button variant="outlined" startIcon={<Refresh />}>
                  刷新数据
                </Button>
              </div>
            </CardContent>
          </Card>
          
          {/* 标签页切换 */}
          <Tabs 
            value={currentTab} 
            onChange={(_, newValue) => setCurrentTab(newValue)} 
            variant="fullWidth"
            sx={{ mb: 2 }}
          >
            <Tab label="交通播报" icon={<Traffic size={16} />} iconPosition="start" />
            <Tab label="停车点位" icon={<LocalParking size={16} />} iconPosition="start" />
            <Tab label="共享数据" icon={<Share size={16} />} iconPosition="start" />
          </Tabs>
          
          {/* 交通播报内容 */}
          {currentTab === 0 && (
            <Card>
              <CardContent>
                {filteredTrafficEvents.length === 0 ? (
                  <Typography variant="body1" align="center">暂无交通事件数据</Typography>
                ) : (
                  <TableContainer component={Paper}>
                    <Table sx={{ minWidth: 650 }} aria-label="traffic events table">
                      <TableHead>
                        <TableRow>
                          <TableCell>类型</TableCell>
                          <TableCell>标题</TableCell>
                          <TableCell>位置</TableCell>
                          <TableCell>严重程度</TableCell>
                          <TableCell>状态</TableCell>
                          <TableCell>更新时间</TableCell>
                          <TableCell align="right">操作</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {filteredTrafficEvents.map((event) => (
                          <TableRow
                            key={event.id}
                            sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
                          >
                            <TableCell>
                              <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                                {getEventTypeIcon(event.type)}
                                <span>{getEventTypeText(event.type)}</span>
                              </div>
                            </TableCell>
                            <TableCell>{event.title}</TableCell>
                            <TableCell>{event.location}</TableCell>
                            <TableCell>
                              <Chip 
                                label={getSeverityText(event.severity)} 
                                size="small" 
                                sx={getSeverityStyle(event.severity)}
                              />
                            </TableCell>
                            <TableCell>{event.status === 'ongoing' ? '进行中' : '已结束'}</TableCell>
                            <TableCell>{formatTimestamp(event.updateTime)}</TableCell>
                            <TableCell align="right">
                              <Button 
                                variant="text" 
                                color="primary"
                                size="small"
                                onClick={() => handleOpenTrafficDialog(event)}
                              >
                                详情
                              </Button>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                )}
              </CardContent>
            </Card>
          )}
          
          {/* 停车点位内容 */}
          {currentTab === 1 && (
            <Grid container spacing={3}>
              {filteredParkingLots.length === 0 ? (
                <Grid item xs={12}>
                  <Typography variant="body1" align="center">暂无停车场数据</Typography>
                </Grid>
              ) : (
                filteredParkingLots.map((parkingLot) => (
                  <Grid item xs={12} sm={6} md={4} key={parkingLot.id}>
                    <Card variant="outlined" onClick={() => handleOpenParkingDialog(parkingLot)} style={{ cursor: 'pointer', height: '100%' }}>
                      <CardContent>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                          <Typography variant="h6">{parkingLot.name}</Typography>
                          <Chip 
                            label={`${parkingLot.availableSpaces}/${parkingLot.totalSpaces}`}
                            size="small" 
                            sx={getParkingStatusStyle(parkingLot)}
                          />
                        </div>
                        <Typography variant="body2" color="text.secondary" gutterBottom>
                          {parkingLot.address}
                        </Typography>
                        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                          <div>
                            <Typography variant="subtitle2" color="text.secondary">小时费率</Typography>
                            <Typography variant="body1">¥{parkingLot.hourlyRate}</Typography>
                          </div>
                          <div>
                            <Typography variant="subtitle2" color="text.secondary">可用率</Typography>
                            <Typography variant="body1" sx={getParkingStatusStyle(parkingLot)}>
                              {getAvailabilityRate(parkingLot)}%
                            </Typography>
                          </div>
                          <div>
                            <Typography variant="subtitle2" color="text.secondary">评分</Typography>
                            <Typography variant="body1">{parkingLot.rating}★</Typography>
                          </div>
                        </div>
                        <Divider sx={{ my: 1 }} />
                        <Typography variant="subtitle2" gutterBottom>特色服务:</Typography>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                          {parkingLot.features.map((feature, index) => (
                            <Chip key={index} label={feature} size="small" variant="outlined" />
                          ))}
                        </div>
                        <Typography variant="caption" color="text.secondary" style={{ display: 'block', marginTop: 8 }}>
                          数据更新时间: {formatTimestamp(parkingLot.lastUpdated)}
                        </Typography>
                      </CardContent>
                    </Card>
                  </Grid>
                ))
              )}
            </Grid>
          )}
          
          {/* 共享数据内容 */}
          {currentTab === 2 && (
            <Card>
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  共享数据服务
                </Typography>
                <Grid container spacing={3}>
                  <Grid item xs={12} sm={6} md={4}>
                    <Card variant="outlined" sx={{ height: '100%' }}>
                      <CardContent>
                        <Typography variant="subtitle1" gutterBottom>实时路况数据</Typography>
                        <Typography variant="body2" color="text.secondary" gutterBottom>
                          提供全市范围内的实时交通拥堵情况、道路施工信息等。
                        </Typography>
                        <Button variant="outlined" color="primary" size="small">
                          查看详情
                        </Button>
                      </CardContent>
                    </Card>
                  </Grid>
                  <Grid item xs={12} sm={6} md={4}>
                    <Card variant="outlined" sx={{ height: '100%' }}>
                      <CardContent>
                        <Typography variant="subtitle1" gutterBottom>公共充电桩分布</Typography>
                        <Typography variant="body2" color="text.secondary" gutterBottom>
                          提供全市范围内的公共充电桩位置、数量、使用状态等信息。
                        </Typography>
                        <Button variant="outlined" color="primary" size="small">
                          查看详情
                        </Button>
                      </CardContent>
                    </Card>
                  </Grid>
                  <Grid item xs={12} sm={6} md={4}>
                    <Card variant="outlined" sx={{ height: '100%' }}>
                      <CardContent>
                        <Typography variant="subtitle1" gutterBottom>气象预警信息</Typography>
                        <Typography variant="body2" color="text.secondary" gutterBottom>
                          提供实时气象预警信息，包括暴雨、大风、高温等极端天气预警。
                        </Typography>
                        <Button variant="outlined" color="primary" size="small">
                          查看详情
                        </Button>
                      </CardContent>
                    </Card>
                  </Grid>
                </Grid>
              </CardContent>
            </Card>
          )}
        </>
      )}
      
      {/* 交通事件详情对话框 */}
      <Dialog 
        open={trafficDialogOpen} 
        onClose={handleCloseTrafficDialog}
        fullWidth
        maxWidth="md"
      >
        {selectedTrafficEvent && (
          <>
            <DialogTitle>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                {getEventTypeIcon(selectedTrafficEvent.type)}
                {selectedTrafficEvent.title}
              </div>
            </DialogTitle>
            <DialogContent>
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">事件类型</Typography>
                <Typography variant="body1">{getEventTypeText(selectedTrafficEvent.type)}</Typography>
              </div>
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">位置</Typography>
                <Typography variant="body1">{selectedTrafficEvent.location}</Typography>
              </div>
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">严重程度</Typography>
                <Chip 
                  label={getSeverityText(selectedTrafficEvent.severity)} 
                  sx={getSeverityStyle(selectedTrafficEvent.severity)}
                />
              </div>
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">描述</Typography>
                <Typography variant="body1">{selectedTrafficEvent.description}</Typography>
              </div>
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">开始时间</Typography>
                <Typography variant="body1">{formatTimestamp(selectedTrafficEvent.startTime)}</Typography>
              </div>
              {selectedTrafficEvent.endTime && (
                <div style={{ marginBottom: 16 }}>
                  <Typography variant="subtitle2" color="text.secondary">结束时间</Typography>
                  <Typography variant="body1">{formatTimestamp(selectedTrafficEvent.endTime)}</Typography>
                </div>
              )}
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">状态</Typography>
                <Typography variant="body1">{selectedTrafficEvent.status === 'ongoing' ? '进行中' : '已结束'}</Typography>
              </div>
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">数据来源</Typography>
                <Typography variant="body1">{selectedTrafficEvent.source}</Typography>
              </div>
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">更新时间</Typography>
                <Typography variant="body1">{formatTimestamp(selectedTrafficEvent.updateTime)}</Typography>
              </div>
              
              {/* 模拟地图显示 */}
              {selectedTrafficEvent.latitude !== 0 && (
                <div style={{ 
                  height: 200, 
                  width: '100%', 
                  backgroundColor: '#f0f0f0', 
                  position: 'relative',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  marginBottom: 16
                }}>
                  <LocationOn size={32} color="error" />
                  <Typography variant="body1" style={{ position: 'absolute', bottom: 8 }}>
                    {selectedTrafficEvent.location}
                  </Typography>
                </div>
              )}
            </DialogContent>
            <DialogActions>
              <Button onClick={handleCloseTrafficDialog}>关闭</Button>
            </DialogActions>
          </>
        )}
      </Dialog>
      
      {/* 停车场详情对话框 */}
      <Dialog 
        open={parkingDialogOpen} 
        onClose={handleCloseParkingDialog}
        fullWidth
        maxWidth="md"
      >
        {selectedParkingLot && (
          <>
            <DialogTitle>{selectedParkingLot.name}</DialogTitle>
            <DialogContent>
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">地址</Typography>
                <Typography variant="body1">{selectedParkingLot.address}</Typography>
              </div>
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">车位信息</Typography>
                <Typography variant="body1">
                  总车位: {selectedParkingLot.totalSpaces} | 可用车位: {selectedParkingLot.availableSpaces}
                </Typography>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 }}>
                  <Typography variant="body2">可用率:</Typography>
                  <div style={{ flex: 1, height: 8, backgroundColor: '#e0e0e0', borderRadius: 4 }}>
                    <div 
                      style={{
                        width: `${getAvailabilityRate(selectedParkingLot)}%`,
                        height: '100%',
                        backgroundColor: parseFloat(getAvailabilityRate(selectedParkingLot)) > 30 ? '#4caf50' : parseFloat(getAvailabilityRate(selectedParkingLot)) > 10 ? '#ff9800' : '#f44336',
                        borderRadius: 4
                      }}
                    ></div>
                  </div>
                  <Typography variant="body2">{getAvailabilityRate(selectedParkingLot)}%</Typography>
                </div>
              </div>
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">收费标准</Typography>
                <Typography variant="body1">小时费率: ¥{selectedParkingLot.hourlyRate}</Typography>
              </div>
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">营业时间</Typography>
                <Typography variant="body1">{selectedParkingLot.isOpen ? '营业中' : '已关闭'}</Typography>
              </div>
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">评分</Typography>
                <Typography variant="body1">{selectedParkingLot.rating}★</Typography>
              </div>
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">特色服务</Typography>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                  {selectedParkingLot.features.map((feature, index) => (
                    <Chip key={index} label={feature} size="small" />
                  ))}
                </div>
              </div>
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" color="text.secondary">数据更新时间</Typography>
                <Typography variant="body1">{formatTimestamp(selectedParkingLot.lastUpdated)}</Typography>
              </div>
              
              {/* 模拟地图显示 */}
              <div style={{ 
                height: 200, 
                width: '100%', 
                backgroundColor: '#f0f0f0', 
                position: 'relative',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                marginBottom: 16
              }}>
                <LocalParking size={32} color="primary" />
                <Typography variant="body1" style={{ position: 'absolute', bottom: 8 }}>
                  {selectedParkingLot.address}
                </Typography>
              </div>
            </DialogContent>
            <DialogActions>
              <Button onClick={handleCloseParkingDialog}>关闭</Button>
              <Button color="primary">导航到此处</Button>
            </DialogActions>
          </>
        )}
      </Dialog>
    </Box>
  );
};

export default PublicData;